/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package sistemabienes;

import com.sun.data.provider.RowKey;
import com.sun.data.provider.impl.CachedRowSetDataProvider;
import com.sun.rave.web.ui.appbase.AbstractPageBean;
import com.sun.webui.jsf.component.DropDown;
import com.sun.webui.jsf.component.Hyperlink;
import com.sun.webui.jsf.component.PanelLayout;
import com.sun.webui.jsf.component.PasswordField;
import com.sun.webui.jsf.component.TextField;
import com.sun.webui.jsf.model.SingleSelectOptionsList;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.faces.FacesException;
import javax.faces.context.FacesContext;
import javax.faces.convert.NumberConverter;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 * <p>Page bean that corresponds to a similarly named JSP page.  This
 * class contains component definitions (and initialization code) for
 * all components that you have defined on this page, as well as
 * lifecycle methods and event handlers where you may add behavior
 * to respond to incoming events.</p>
 *
 * @version crearUsuario.java
 * @version Created on 06-12-2011, 12:14:56 PM
 * @author luis
 */

public class crearUsuario extends AbstractPageBean {
    // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">

    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
        dropDown1DefaultOptions.setOptions(new com.sun.webui.jsf.model.Option[]{new com.sun.webui.jsf.model.Option("-1", "eliga seccion"), new com.sun.webui.jsf.model.Option("1", "edilicios"), new com.sun.webui.jsf.model.Option("2", "salud"), new com.sun.webui.jsf.model.Option("3", "educacion")});
        usuarioDataProvider2.setCachedRowSet((javax.sql.rowset.CachedRowSet) getValue("#{SessionBean1.usuarioRowSet2}"));
        numberConverter1.setMinIntegerDigits(1);
        numberConverter1.setMaxIntegerDigits(40);
        numberConverter1.setMaxFractionDigits(3);
    }
    private SingleSelectOptionsList dropDown1DefaultOptions = new SingleSelectOptionsList();

    public SingleSelectOptionsList getDropDown1DefaultOptions() {
        return dropDown1DefaultOptions;
    }

    public void setDropDown1DefaultOptions(SingleSelectOptionsList ssol) {
        this.dropDown1DefaultOptions = ssol;
    }
    private CachedRowSetDataProvider usuarioDataProvider2 = new CachedRowSetDataProvider();

    public CachedRowSetDataProvider getUsuarioDataProvider2() {
        return usuarioDataProvider2;
    }

    public void setUsuarioDataProvider2(CachedRowSetDataProvider crsdp) {
        this.usuarioDataProvider2 = crsdp;
    }
    private TextField textField1 = new TextField();

    public TextField getTextField1() {
        return textField1;
    }

    public void setTextField1(TextField tf) {
        this.textField1 = tf;
    }
    private DropDown dropDown1 = new DropDown();

    public DropDown getDropDown1() {
        return dropDown1;
    }

    public void setDropDown1(DropDown dd) {
        this.dropDown1 = dd;
    }
    private PasswordField passwordField1 = new PasswordField();

    public PasswordField getPasswordField1() {
        return passwordField1;
    }

    public void setPasswordField1(PasswordField pf) {
        this.passwordField1 = pf;
    }
    private PasswordField passwordField2 = new PasswordField();

    public PasswordField getPasswordField2() {
        return passwordField2;
    }

    public void setPasswordField2(PasswordField pf) {
        this.passwordField2 = pf;
    }
    private PanelLayout layoutPanel1 = new PanelLayout();

    public PanelLayout getLayoutPanel1() {
        return layoutPanel1;
    }

    public void setLayoutPanel1(PanelLayout pl) {
        this.layoutPanel1 = pl;
    }
    private PanelLayout layoutPanel2 = new PanelLayout();

    public PanelLayout getLayoutPanel2() {
        return layoutPanel2;
    }

    public void setLayoutPanel2(PanelLayout pl) {
        this.layoutPanel2 = pl;
    }
    private SingleSelectOptionsList dropDown2DefaultOptions = new SingleSelectOptionsList();

    public SingleSelectOptionsList getDropDown2DefaultOptions() {
        return dropDown2DefaultOptions;
    }

    public void setDropDown2DefaultOptions(SingleSelectOptionsList ssol) {
        this.dropDown2DefaultOptions = ssol;
    }
    private NumberConverter numberConverter1 = new NumberConverter();

    public NumberConverter getNumberConverter1() {
        return numberConverter1;
    }

    public void setNumberConverter1(NumberConverter nc) {
        this.numberConverter1 = nc;
    }

    // </editor-fold>

    /**
     * <p>Construct a new Page bean instance.</p>
     */
    public crearUsuario() {
    }

    /**
     * <p>Callback method that is called whenever a page is navigated to,
     * either directly via a URL, or indirectly via page navigation.
     * Customize this method to acquire resources that will be needed
     * for event handlers and lifecycle methods, whether or not this
     * page is performing post back processing.</p>
     * 
     * <p>Note that, if the current request is a postback, the property
     * values of the components do <strong>not</strong> represent any
     * values submitted with this request.  Instead, they represent the
     * property values that were saved for this view when it was rendered.</p>
     */
    @Override
    public void init() {
        // Perform initializations inherited from our superclass
        super.init();
        // Perform application initialization that must complete
        // *before* managed components are initialized
        // TODO - add your own initialiation code here
       // layoutPanel1.setVisible(true);
        //layoutPanel2.setVisible(false);
        textField1.setValue(null);
        passwordField1.setValue(null);
        passwordField2.setValue(null);
        // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("crearUsuario Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e: new FacesException(e);
        }
        
        // </editor-fold>
        // Perform application initialization that must complete
        // *after* managed components are initialized
        // TODO - add your own initialization code here
    }

    /**
     * <p>Callback method that is called after the component tree has been
     * restored, but before any event processing takes place.  This method
     * will <strong>only</strong> be called on a postback request that
     * is processing a form submit.  Customize this method to allocate
     * resources that will be required in your event handlers.</p>
     */
    @Override
    public void preprocess() {
    }

    /**
     * <p>Callback method that is called just before rendering takes place.
     * This method will <strong>only</strong> be called for the page that
     * will actually be rendered (and not, for example, on a page that
     * handled a postback and then navigated to a different page).  Customize
     * this method to allocate resources that will be required for rendering
     * this page.</p>
     */
    @Override
    public void prerender() {

    }

    /**
     * <p>Callback method that is called after rendering is completed for
     * this request, if <code>init()</code> was called (regardless of whether
     * or not this was the page that was actually rendered).  Customize this
     * method to release resources acquired in the <code>init()</code>,
     * <code>preprocess()</code>, or <code>prerender()</code> methods (or
     * acquired during execution of an event handler).</p>
     */
    @Override
    public void destroy() {
        usuarioDataProvider2.close();
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected SessionBean1 getSessionBean1() {
        return (SessionBean1) getBean("SessionBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected ApplicationBean1 getApplicationBean1() {
        return (ApplicationBean1) getBean("ApplicationBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected RequestBean1 getRequestBean1() {
        return (RequestBean1) getBean("RequestBean1");
    }

    public String button1_action() throws NamingException {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        if (textField1.getText().toString() != null || textField1.getText().toString().length() > 0)
        {
            if (passwordField1.getText().toString() != null || passwordField1.getText().toString().length() > 0)
            {
                if (passwordField2.getText().toString() != null || passwordField2.getText().toString().length() > 0)
                {      String seccion=dropDown1.getValue().toString();
                       String habilitado="1";
                 if(!seccion.equals("-1"))
                 {
                       if(usuarioDataProvider2.getRowCount()>0)
                    {
                            String usuario=textField1.getText().toString();
                            String password=passwordField1.getText().toString();
                            String password2=passwordField2.getText().toString();
                            
                            
                            if(password.equals(password2))
                            {
                                   RowKey fila= usuarioDataProvider2.findFirst("NOMBRE_USUARIO", usuario);                
                                         if(fila==null){
                                             String md=md5.encriptar(password);
                                             int sec=buscar_max_usuario();
                                                usuarioDataProvider2.cursorFirst();
                                                boolean s[] = {true, true, true,true,true,false};
                                                RowKey row2=usuarioDataProvider2.appendRow();
                                                this.getSessionBean1().getUsuarioRowSet2().setInsertableColumns(s);
                                                this.usuarioDataProvider2.setValue("KEYUSUARIO",row2, sec);
                                                this.usuarioDataProvider2.setValue("NOMBRE_USUARIO",row2, usuario);
                                                this.usuarioDataProvider2.setValue("PASSWORD",row2, md);
                                                this.usuarioDataProvider2.setValue("SECCION",row2, seccion);
                                                 this.usuarioDataProvider2.setValue("ACTIVO",row2, habilitado);
                                                 this.usuarioDataProvider2.commitChanges();
                                                  error("Se creo el usuario exitosamente");
                                        }else{
                                                error("Este nombre de usuario ya esta registrado");

                                        }
                              }else{error("Password no coincide vuelva  a escribir");}
                    
                    }else{
                            String password=passwordField1.getText().toString();
                            String password2=passwordField2.getText().toString();
                            if(password.equals(password2))
                                {

                            String md=md5.encriptar(password);
                            int sec=buscar_max_usuario();
                            usuarioDataProvider2.cursorFirst();
                            boolean s[] = {true, true, true,true,true,false};
                            RowKey row2=usuarioDataProvider2.appendRow();
                            this.getSessionBean1().getUsuarioRowSet2().setInsertableColumns(s);
                            this.usuarioDataProvider2.setValue("KEYUSUARIO",row2, sec);
                            this.usuarioDataProvider2.setValue("NOMBRE_USUARIO",row2, md);
                            this.usuarioDataProvider2.setValue("PASSWORD",row2, md);
                            this.usuarioDataProvider2.setValue("SECCION",row2, seccion);
                             this.usuarioDataProvider2.setValue("SECCION",row2, habilitado);
                             this.usuarioDataProvider2.commitChanges();
                             error("Se creo el usuario exitosamente");
                                }else{error("Password no coincide vuelva  a escribir");}
                    }
            //listbox1.setVisible(true);
            //table1.setVisible(true);
                }
            }
          }
        }
        return null;
    }
    public int buscar_max_usuario() throws NamingException
    {
        int secuencia=0;
            try{
                String dataSourceName=
                        this.getSessionBean1().getUsuarioRowSet2().getDataSourceName();
                 Context ctx= new InitialContext();
                 DataSource ds=(DataSource) ctx.lookup(dataSourceName);

                 CallableStatement cs1 = ds.getConnection().prepareCall("select max(keyusuario) as secuencia from usuario");
                   ResultSet rs=cs1.executeQuery();
                 if(rs.next())
                 {
                     int valor=rs.getInt(1);
                     secuencia=valor+1;
                     rs.close();
                      return secuencia;
                 }
                  /* do
                   {
                       
                   }while (rs.next());*/
                   
                
     }catch(SQLException e)
            {
                error(e.getMessage());

            }
        return 0;
    }

    public void button2_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.

        try{
                        FacesContext contex = FacesContext.getCurrentInstance();
                        contex.getExternalContext().redirect( "/SistemaBienes/faces/crearUsuario.jsp" );
            }catch(  Exception e ){
             error( " no funciona esta redireccion" );
                }
    }

    public void hyperlink2_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        try{
                        layoutPanel1.setVisible(true);
                        layoutPanel2.setVisible(false);
                        FacesContext contex = FacesContext.getCurrentInstance();
                        contex.getExternalContext().redirect( "/SistemaBienes/faces/crearUsuario.jsp" );
                        
            }catch(  Exception e ){
             error( " no funciona esta redireccion" );
                }
        
    }

    public void hyperlink3_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
         try{
                        layoutPanel1.setVisible(false);
                        layoutPanel2.setVisible(true);
                        FacesContext contex = FacesContext.getCurrentInstance();
                        contex.getExternalContext().redirect( "/SistemaBienes/faces/crearUsuario.jsp" );
                        
            }catch(  Exception e ){
             error( " no funciona esta redireccion" );
                }
    }

    public String lkufv_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return null;
    }
    
    
    
}

